// 并发控制

// 创建一个异步任务
function createTask(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(`Task ${id} is done!`);
      resolve(id);
    }, id * 1000)
  });
}

function runTasks(tasks, maxConcurrent) {
  let runningTasks = 0; // 当前运行的任务数
  let taskIndex = 0;    // 当前任务索引

  return new Promise((resolve) => {
    function runNext() {
      // 如果当前运行的任务小于最大并发数且还有任务未开始，继续执行任务
      while (runningTasks < maxConcurrent && taskIndex < tasks.length) {
        const currentTask = tasks[taskIndex++];
        runningTasks++;

        currentTask.then(() => {
          runningTasks--; // 任务完成后减少当前运行数
          runNext(); // 继续执行下一个任务
        });
      }

      // 当所有任务完成后，结束
      if (runningTasks === 0 && taskIndex === tasks.length) {
        resolve();
      }
    }

    runNext(); // 开始执行任务
  });
}


function main() {
  const tasks = new Array(20).fill(0).map((_, i) => createTask(i));
  runTasks(tasks, 8);
}

main();
